import {LockOutlined} from '@ant-design/icons';
import {Button, Form, Input, message} from 'antd';
import React from 'react';

interface AlterPasswordProp {
  handleUpdate: (values: any) => Promise<void>
}

const AlterPassword: React.FC<AlterPasswordProp> = ({handleUpdate}) => {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = React.useState(false);

  const onFinish = async (values: any) => {
    try {
      setSubmitting(true);
      await handleUpdate(values)
    } catch (error) {
      message.error('修改密码出错，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Form
      form={form}
      name="alter_password"
      onFinish={onFinish}
      layout="vertical"
      style={{maxWidth: 400}}
    >
      <Form.Item
        name="oldPassword"
        label="当前密码"
        rules={[
          {required: true, message: '请输入当前密码'},
          {min: 6, message: '密码长度至少6位'},
        ]}
      >
        <Input.Password
          prefix={<LockOutlined/>}
          placeholder="请输入当前密码"
        />
      </Form.Item>

      <Form.Item
        name="newPassword"
        label="新密码"
        rules={[
          {required: true, message: '请输入新密码'},
          {min: 6, message: '密码长度至少6位'},
        ]}
        hasFeedback
      >
        <Input.Password
          prefix={<LockOutlined/>}
          placeholder="请输入新密码"
        />
      </Form.Item>

      <Form.Item
        name="confirmPassword"
        label="确认新密码"
        rules={[
          {required: true, message: '请确认新密码'},
        ]}
      >
        <Input.Password
          prefix={<LockOutlined/>}
          placeholder="请再次输入新密码"
        />
      </Form.Item>

      <Form.Item>
        <Button
          type="primary"
          htmlType="submit"
          loading={submitting}
          style={{width: '100%'}}
        >
          确认修改
        </Button>
      </Form.Item>
    </Form>
  );
};

export default AlterPassword;
